package com.maserb.monitor.service.author.impl;

import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.service.author.AuthorService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthorServiceImpl implements AuthorService {

    @Autowired
    PasswordService passwordService;

    @Override
    public void login(UserEntity user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated())
            subject.logout();
        subject.login(token);
    }

    @Override
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated())
            subject.logout();
    }

    public String encryptPassword(String password) {
        return passwordService.encryptPassword(password);
    }

    @Override
    public UserEntity getAuthorizedUser() {
        UserEntity user = (UserEntity) SecurityUtils.getSubject().getPrincipal();
        return user;
    }
}
